<template>
  <el-form ref="form" :model="form" :rules="rules" label-width="80px">
    <el-form-item label="用户名" prop="username">
      <el-input v-model="form.username" maxlength="30" />
    </el-form-item>
    <el-form-item label="手机号码" prop="phone">
      <el-input v-model="form.phone" maxlength="11" />
    </el-form-item>
    <el-form-item label="邮箱" prop="email">
      <el-input v-model="form.email" maxlength="50" />
    </el-form-item>
    <el-form-item label="性别" prop="sex">
      <el-radio-group v-model="form.sex">
        <el-radio :label="0">男</el-radio>
        <el-radio :label="1">女</el-radio>
        <el-radio :label="2">未知</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" size="mini" @click="submit">保存</el-button>
      <el-button type="danger" size="mini" @click="close">关闭</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { updateUserProfile } from "@/api/system/user";

export default {
  props: {
    user: {
      type: Object
    }
  },
  data() {
    return {
      form: {},
      // 表单校验
      rules: {
        username: [
          { required: true, trigger: "blur", message: "请输入您的用户名" },
          { min: 5, max: 20, message: '用户名长度必须在5到20个字符之间', trigger: 'blur' },
          { pattern: /^[a-zA-Z0-9_]+$/, message: '只能使用字母、数字、下划线', trigger: 'blur' }
        ],
        phone: [
          { required: true, trigger: "blur", message: "请输入您的手机号" },
          { min: 11, max: 11, message: '手机号必须是11数字', trigger: 'blur' },
          { pattern: /^[0-9]+$/, message: '只能使用数字', trigger: 'blur' }
        ],
        email: [
          { required: true, trigger: "blur", message: "请输入您的邮箱" },
          { pattern: /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/, message: '不是一个合法的电子邮件地址', trigger: 'blur' }
        ],
        sex: [{ required: true, trigger: "change", message: "请选择性别" }]
      }
    };
  },
  watch: {
    user: {
      handler(user) {
        if (user) {
          this.form = { username: user.username, phone: user.phone, email: user.email, sex: user.sex };
        }
      },
      immediate: true
    }
  },
  methods: {
    submit() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          updateUserProfile(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.user.username = this.form.username;
            this.user.phone = this.form.phone;
            this.user.email = this.form.email;
            this.user.sex = this.form.sex;
          });
        }
      });
    },
    close() {
      this.$tab.closePage();
    }
  }
};
</script>
